package top.tenebrous.termbor.rpc.consumer.nativeTest.consumer;

import cn.hutool.json.JSONUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import top.tenebrous.termbor.rpc.protocol.RpcProtocol;
import top.tenebrous.termbor.rpc.protocol.header.RpcHeaderFactory;
import top.tenebrous.termbor.rpc.protocol.message.RpcRequest;
import top.tenebrous.termbor.rpc.protocol.message.RpcResponse;

public class RpcTestConsumerHandler extends SimpleChannelInboundHandler<RpcProtocol<RpcResponse>> {

    private final Logger logger = LoggerFactory.getLogger(RpcTestConsumerHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("发送数据开始...");
        RpcProtocol<RpcRequest> protocol = new RpcProtocol<>();
        protocol.setHeader(RpcHeaderFactory.getRequestHeader("jdk"));
        RpcRequest request = new RpcRequest();
        request.setClassName("top.tenebrous.jestic.rpc.server.api.HelloService");
        request.setGroup("jestic");
        request.setMethodName("sayHello");
        request.setParameters(new Object[]{"张三"});
        request.setParameterTypes(new Class[]{String.class});
        request.setVersion("1.0.0");
        request.setAsync(false);
        request.setOneway(false);
        protocol.setBody(request);
        logger.info("服务消费者发送的数据为:{}", JSONUtil.toJsonStr(protocol));
//        ctx.writeAndFlush(Unpooled.buffer().writeBytes(JSONUtil.toJsonStr(protocol).getBytes()));
        ctx.writeAndFlush(protocol);
        logger.info("发送数据完毕");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx,
        RpcProtocol<RpcResponse> rpcResponseRpcProtocol) throws Exception {
        logger.info("接收到服务提供者返回的数据为:{}", JSONUtil.toJsonStr(rpcResponseRpcProtocol));
    }
}